package com.store.pet.petstore.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.squareup.picasso.Picasso;
import com.store.pet.petstore.R;
import com.store.pet.petstore.bean.CommodityBean;
import com.store.pet.petstore.bean.MessageBean;
import com.store.pet.petstore.util.Constant;
import com.store.pet.petstore.util.DateUtil;
import com.store.pet.petstore.util.GsonUtils;
import com.store.pet.petstore.util.OKHttpUtils;
import com.store.pet.petstore.widget.BaseDialog;

import java.io.File;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import jsc.kit.wheel.dialog.DateTimeWheelDialog;

import static com.store.pet.petstore.activity.MyCommodityActivity.TASK_SUCCESS;
import static com.store.pet.petstore.activity.MyCommodityActivity.UPDATE_SUCCESS;

public class EditCommodityActivity extends BaseActivity {

    @BindView(R.id.my_status)
    View myStatus;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.petname_et)
    EditText petnameEt;
    @BindView(R.id.price_et)
    EditText priceEt;
    @BindView(R.id.birthday_tv)
    TextView birthdayTv;
    @BindView(R.id.describe_et)
    EditText describeEt;
    @BindView(R.id.commodity_img)
    ImageView commodityImg;
    @BindView(R.id.commit)
    Button commit;
    @BindView(R.id.btn1)
    RadioButton btn1;
    @BindView(R.id.btn2)
    RadioButton btn2;
    @BindView(R.id.btn3)
    RadioButton btn3;

    private String birthday = "";  //生日

    private int type = 0;  //宠物类型

    private String picturePath = "";  //图片路径

    String imgUrls = "";

    /*图片选择*/
    private BaseDialog mPetImageDialog;

    /*选择图片*/
    private static final int REQUEST_PET_IMAGE = 0x0001;

    private boolean isEdit = false;

    private CommodityBean.ContentBean.PetlistBean data;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public int getLayoutID() {
        return R.layout.activity_edit_commodity;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        //沉浸式标题栏
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        takeLinearStatusBar(myStatus);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationIcon(R.drawable.fanhui);  //设置左上角图标
        toolbar.setNavigationOnClickListener(view -> finish());  //退出
        isEdit = getIntent().getBooleanExtra("isEdit", false);
        initDialog();  //加载弹窗
    }

    /**
     * 加载监听器
     */
    private void initListener() {
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                RadioButton rb = findViewById(i);
                switch (rb.getText().toString()) {
                    case "狗狗":
                        type = 1;
                        break;
                    case "猫猫":
                        type = 2;
                        break;
                    case "小宠":
                        type = 3;
                        break;
                }
            }
        });
    }

    /**
     * 加载弹窗
     */
    private void initDialog() {
        mPetImageDialog = new BaseDialog(this) {
            @Override
            public int getLayoutResId() {
                return R.layout.dialog_photo_choose_zhao;
            }
        };
        mPetImageDialog.setGravity(Gravity.BOTTOM);
        mPetImageDialog.setAnimation(R.style.DialogBottomAnim);
        LinearLayout zhaoPaizhao = mPetImageDialog.findViewById(R.id.zhao_paizhao);
        LinearLayout zhaoXiangce = mPetImageDialog.findViewById(R.id.zhao_xiangce);
        Button zhaoMtvmquxiao = mPetImageDialog.findViewById(R.id.zhao_mTvmQuxiao);

        zhaoMtvmquxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //取消
                mPetImageDialog.dismiss();
            }
        });
        zhaoXiangce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //相册
                SingleSelectImg();
                mPetImageDialog.dismiss();
            }
        });
        zhaoPaizhao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //拍照
                openCamera();
                mPetImageDialog.dismiss();
            }
        });
    }

    /**
     * 单选图片
     */
    private void SingleSelectImg() {
        PictureSelector.create(this).openGallery(PictureMimeType.ofImage())
                .isCamera(false)
                .selectionMode(PictureConfig.SINGLE)
                .enableCrop(true)
                .withAspectRatio(1, 1)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(true)
                .showCropGrid(true)
                .compress(true)
                .forResult(REQUEST_PET_IMAGE);
    }

    /*打开摄像机*/
    private void openCamera() {
        PictureSelector.create(this).openCamera(PictureMimeType.ofImage())
                .compress(true)
                .enableCrop(true)
                .withAspectRatio(1, 1)
                .freeStyleCropEnabled(false)
                .circleDimmedLayer(false)
                .showCropFrame(true)
                .showCropGrid(true)
                .forResult(REQUEST_PET_IMAGE);
    }

    /**
     * 获取图片回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case REQUEST_PET_IMAGE://图片
                    final List<LocalMedia> localMedia = PictureSelector.obtainMultipleResult(data);
                    picturePath = localMedia.get(0).getCompressPath();  //图片路径
                    //Picasso显示本地图片
                    String realPath = "file://" + new File(picturePath).getPath();
                    Picasso.with(this).load(realPath).into(commodityImg);
                    break;

            }
        }
    }

    @Override
    public void loadData() {
        if (isEdit) {
            data = (CommodityBean.ContentBean.PetlistBean) getIntent().getSerializableExtra("commodity");
            switch (data.getType()){
                case 1:
                    btn1.setChecked(true);
                    type = 1;
                    break;
                case 2:
                    btn2.setChecked(true);
                    type = 2;
                    break;
                case 3:
                    btn3.setChecked(true);
                    type = 3;
                    break;
            }
            petnameEt.setText(data.getName());
            priceEt.setText(data.getPrice());
            birthdayTv.setText(data.getBirthday());
            describeEt.setText(data.getDescription());
            Picasso.with(this).load(data.getImg()).into(commodityImg);
        }
        initListener();  //加载监听器
    }

    @OnClick({R.id.birthday_tv, R.id.commodity_img, R.id.commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.birthday_tv:
                showTimeDialog(3);
                break;
            case R.id.commodity_img:
                mPetImageDialog.show();
                break;
            case R.id.commit:
                if (isEdit) {
                    //编辑商品
                    if (type != 0 && !petnameEt.getText().toString().equals("") && !priceEt.getText().toString().equals("")
                            && !birthdayTv.getText().toString().equals("1970-01-01") && !describeEt.getText().toString().equals("")) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("petid",data.getId());
                        map.put("name", petnameEt.getText().toString());
                        map.put("type", type);
                        map.put("price", priceEt.getText().toString());
                        map.put("birthday", birthdayTv.getText());
                        map.put("description", describeEt.getText().toString());
                        File file;
                        if(picturePath.equals("")){
                            file = null;
                        }else {
                            file= new File(picturePath);
                        }
                        OKHttpUtils.postPicture(Constant.UPDATE_COMMODITY, file, map, new OKHttpUtils.ServerCallBack() {
                            @Override
                            public void onSuccess(String data) {
                                MessageBean msg = GsonUtils.parseMessage(data);
                                if (msg.getCode() == 106) {
                                    setResult(UPDATE_SUCCESS, new Intent());
                                    finish();
                                }
                                ToastUtils.showShort(msg.getMsg());
                            }

                            @Override
                            public void onFailed(String message) {
                                ToastUtils.showShort("修改失败");
                            }
                        });
                    } else {
                        ToastUtils.showShort("请输入完整");
                    }
                } else {
                    //添加商品
                    if (type != 0 && !petnameEt.getText().toString().equals("") && !priceEt.getText().toString().equals("")
                            && !birthdayTv.getText().toString().equals("1970-01-01") && !describeEt.getText().toString().equals("")
                            && !picturePath.equals("")) {
                        Map<String, Object> map = new HashMap<>();
                        map.put("name", petnameEt.getText().toString());
                        map.put("type", type);
                        map.put("price", priceEt.getText().toString());
                        map.put("sellerid", getMyId());
                        map.put("birthday", birthday);
                        map.put("description", describeEt.getText().toString());
                        File file = new File(picturePath);
                        OKHttpUtils.postPicture(Constant.ADD_COMMODITY, file, map, new OKHttpUtils.ServerCallBack() {
                            @Override
                            public void onSuccess(String data) {
                                MessageBean msg = GsonUtils.parseMessage(data);
                                if (msg.getCode() == 105) {
                                    setResult(TASK_SUCCESS, new Intent());
                                    finish();
                                }
                                ToastUtils.showShort(msg.getMsg());
                            }

                            @Override
                            public void onFailed(String message) {
                                ToastUtils.showShort("添加失败");
                            }
                        });
                    } else {
                        ToastUtils.showShort("请输入完整");
                    }
                }
                break;
        }
    }

    public void showTimeDialog(int type) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 1970);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 2);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        Date startDate = calendar.getTime();
        calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, 2020);
        Date endDate = calendar.getTime();

        DateTimeWheelDialog dialog = new DateTimeWheelDialog(this);
        dialog.show();
        dialog.setTitle("选择时间");
        int config = DateTimeWheelDialog.SHOW_YEAR_MONTH_DAY_HOUR_MINUTE;
        switch (type) {
            case 1://只显示年
                config = DateTimeWheelDialog.SHOW_YEAR;
                break;
            case 2://显示年、月
                config = DateTimeWheelDialog.SHOW_YEAR_MONTH;
                break;
            case 3://显示年、月、日
                config = DateTimeWheelDialog.SHOW_YEAR_MONTH_DAY;
                break;
            case 4://显示年、月、日、时
                config = DateTimeWheelDialog.SHOW_YEAR_MONTH_DAY_HOUR;
                break;
            case 5://显示年、月、日、时、分
                config = DateTimeWheelDialog.SHOW_YEAR_MONTH_DAY_HOUR_MINUTE;
                break;
        }
        dialog.configShowUI(config);
        dialog.setCancelButton("取消", null);
        dialog.setOKButton("确定", new DateTimeWheelDialog.OnClickCallBack() {
            @Override
            public boolean callBack(View v, @NonNull Date selectedDate) {
                birthday = DateUtil.getDateToString3(selectedDate.getTime());
                birthdayTv.setText(birthday);
                return false;
            }
        });
        dialog.setDateArea(startDate, endDate, true);
        dialog.updateSelectedDate(new Date());
    }
}
